package edu.csl.study.springboot.common;

import edu.csl.study.springboot.common.exception.BusinessException;
import edu.csl.study.springboot.common.exception.ErrorDefine;
import edu.csl.study.springboot.common.exception.ErrorDefineInterface;
import lombok.Data;

@Data
public class ApiResponse {
    /**
     * 响应代码
     */
    private String code = "0000";
    /**
     * 响应消息
     */
    private String message = "Success";
    private Object data;
    public ApiResponse(){

    }
    public static ApiResponse success(Object data){
        ApiResponse apiResponse= new ApiResponse();
        apiResponse.code = "0000";
        apiResponse.message = "Success";
        apiResponse.data = data;
        return  apiResponse;
    }
    public static ApiResponse error(Object data){
        ApiResponse apiResponse= new ApiResponse();

        if ((data instanceof Exception)) {
            apiResponse.code = "9999";
            apiResponse.message = "服务异常："+((Exception)data).getLocalizedMessage();
        }else if ((data instanceof BusinessException)) {
            apiResponse.code = ((BusinessException)data).getErrorCode();
            apiResponse.message = "业务校验失败："+((BusinessException)data).getMessage();
        }else if ((data instanceof String)) {
            apiResponse.code = "9999";
            apiResponse.message = ((Exception)data).getLocalizedMessage();
        }
        return apiResponse;
    }
    public static ApiResponse error(String code,String message){
        ApiResponse apiResponse= new ApiResponse();
        apiResponse.code = code;
        apiResponse.message = message;
        return apiResponse;
    }
    public static ApiResponse error(ErrorDefine errorDefine){
        ApiResponse apiResponse= new ApiResponse();
        apiResponse.code = errorDefine.getCode();
        apiResponse.message = errorDefine.getMessage();
        return apiResponse;
    }
    public static ApiResponse error(ErrorDefineInterface errorDefine){
        ApiResponse apiResponse= new ApiResponse();
        apiResponse.code = errorDefine.getCode();
        apiResponse.message = errorDefine.getMessage();
        return apiResponse;
    }

}
